package com.ethink.framework.feign;

import com.alibaba.fastjson.JSON;
import com.ethink.framework.common.constant.CommonConstant;
import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.framework.common.exception.FacadeException;
import com.ethink.framework.common.web.response.CommonResponse;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;

import java.io.IOException;

import static feign.FeignException.errorStatus;

@Slf4j
public class DefaultErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        String body = null;
        try {
            body = IOUtils.toString(response.body().asReader(CommonConstant.CHARSET_UTF8));
            log.error("methodKey:{}, status:{}, body:{}", methodKey, response.status(), body);
        } catch (IOException e) {
            log.error("feign调用异常处理失败", e);
        }
        if (response.status() == 500) {
            CommonResponse commonResponse = JSON.parseObject(body, CommonResponse.class);
            throw new BusinessException(commonResponse.getCode(), commonResponse.getMessage());
        }
        Exception e = errorStatus(methodKey, response);
        log.error("服务调用异常", e);
        throw new FacadeException(CommonRespCode.FACADE_CALL_ERROR);
    }
}
